package com.aishua.aishuawallet.activity;

import android.content.Context;
import android.content.Intent;
import android.media.midi.MidiDeviceService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.R;
import com.aishua.aishuawallet.bean.ResAuthBean;
import com.aishua.aishuawallet.bean.TokenInfo;
import com.aishua.aishuawallet.business.TaskBusiness;
import com.aishua.aishuawallet.diydialog.LoadingDialog;
import com.aishua.aishuawallet.diydialog.xLoadingDialog;
import com.aishua.aishuawallet.longconnection.ClientSocket;
import com.aishua.aishuawallet.mina.MianManager;
import com.aishua.aishuawallet.mina.MinaResultLIstener;
import com.aishua.aishuawallet.utils.AndroidUtils;
import com.aishua.aishuawallet.utils.LogUtils;

import org.apache.mina.core.session.IoSession;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by aishua on 2018/8/8.
 */

public class CreatWallettwoActivity extends BaseActivity {

    private static final String TAG = "CreatWallettwoActivity-";
    private Toolbar tl_creatwallet;
    private EditText et_name;
    private EditText et_pw;
    private EditText et_pwagain;
    private EditText et_pwinfo;
    private CheckBox cb_agree;
    private TextView tv_agreement;
    private Button btn_createwallet;
    private Context mContext;
    private ArrayList<TokenInfo> tokeninfoList;
    private String walletname;
    private String pwinfo;
    private xLoadingDialog loadingDialog;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadingDialog.dismiss();
            switch (msg.what) {

                case 6:

                    ResAuthBean resAuthBean = (ResAuthBean) msg.getData().getSerializable("resAuthBean");

                    notifyCreateSuc(resAuthBean);


                    break;
                case 7:
                    Toast.makeText(mContext, "Token生成失败", Toast.LENGTH_SHORT).show();

                    break;
            }


        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creatwallettwo);
        mContext = this;
        initToolbar();
        initView();
        initData();
    }


    private void initView() {

        et_name = findViewById(R.id.et_name);
        et_pw = findViewById(R.id.et_pw);
        et_pwagain = findViewById(R.id.et_pwagain);
        et_pwinfo = findViewById(R.id.et_pwinfo);
        cb_agree = findViewById(R.id.cb_agree);
        tv_agreement = findViewById(R.id.tv_agreement);
        btn_createwallet = findViewById(R.id.btn_createwallet);
        MyTextWatcher1 myTextWatcher1 = new MyTextWatcher1();
        MyTextWatcher2 myTextWatcher2 = new MyTextWatcher2();
        et_name.addTextChangedListener(myTextWatcher1);
        et_pwinfo.addTextChangedListener(myTextWatcher2);
    }

    private void initToolbar() {

        tl_creatwallet = findViewById(R.id.tl_creatwallet);
        tl_creatwallet.setTitle("");
        setSupportActionBar(tl_creatwallet);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tl_creatwallet.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

    }

    private void initData() {

        btn_createwallet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!cb_agree.isChecked()) {

                    Toast.makeText(CreatWallettwoActivity.this, "请先同意协议", Toast.LENGTH_SHORT).show();
                    return;
                }

                final String name = et_name.getText().toString().trim();
                if (null == name || "".equals(name)) {

                    Toast.makeText(CreatWallettwoActivity.this, "请输入钱包名称", Toast.LENGTH_SHORT).show();
                    return;
                }

                loadingDialog = xLoadingDialog.newInstance(getResources().getString(R.string.creatwallet));
//                loadingDialog.setCancelable(false);
                loadingDialog.show(getFragmentManager(), "create");
                TaskBusiness.getInstance().TokenCreate(getApplicationContext(), name, new MinaResultLIstener() {
                    @Override
                    public void messageReceived(IoSession session, Object message) {

                        String msg = message.toString();
                        LogUtils.v(TAG + "msg:" + msg);
                        String commandid = msg.substring(12, 16);
                        String time= msg.substring(70,74);
                        LogUtils.v(TAG+"TIME:"+time);
                        String result = msg.substring(74, 76);
                        LogUtils.v(TAG+"commandid："+commandid+"result:"+result);
                        if (commandid.equals("4011") && result.equals("00")){

                            LogUtils.v(TAG+"钱包创建请求发送成功");

                        }else if (commandid.equals("5010") && result.equals("00")) {
                            LogUtils.v(TAG+"token创建成功");
                            MianManager.getManager().shutDown();
                            String tokenid = msg.substring(78, 94);
                            LogUtils.v(TAG+"tokenid:"+tokenid);
                            int tokenamelen = Integer.parseInt(msg.substring(94, 96), 16);
                            LogUtils.v(TAG+"tokenamelen:"+tokenamelen);
                            int end = 96 + tokenamelen;
                            String tokenname = msg.substring(96, 96 + tokenamelen);
                            String tokenaddr = msg.substring(end, end + 40);
                            tokenname = AndroidUtils.unicode2String(tokenname);

                            LogUtils.v(TAG+"tokenname:"+tokenname+"tokenaddr:"+tokenaddr+"tokenid:"+tokenid);
                            Message message1 = Message.obtain();
                            ResAuthBean resAuthBean = new ResAuthBean();
                            resAuthBean.setTokenNum("1");
                            TokenInfo tokenInfo = new TokenInfo();
                            tokeninfoList = new ArrayList<>();
                            resAuthBean.setResult(result);
                            tokenInfo.setTokenID(tokenid);
                            tokenInfo.setTokenName(tokenname);
                            tokenInfo.setTokenAddr(tokenaddr);
                            tokeninfoList.add(tokenInfo);
                            resAuthBean.setTokenInfo(tokeninfoList);
                            Bundle bundle = message1.getData();
                            bundle.putSerializable("resAuthBean", (Serializable) resAuthBean);
                            message1.what = Constant.TOKEN_CREAT_SUCCESS;
                            mHandler.sendMessage(message1);

                        } else {

                            MianManager.getManager().shutDown();
                            mHandler.sendEmptyMessage(Constant.TOKEN_CREAT_FAIL);
                        }

                    }

                    @Override
                    public void exceptionCaught(IoSession session, Throwable cause) {


                        MianManager.getManager().shutDown();
                        LogUtils.v(TAG + "failmsg:" + cause.getMessage());

                    }

                });

            }
        });

    }

    private void notifyCreateSuc(ResAuthBean resAuthBean) {


        TaskBusiness.getInstance().NotifyCreatSuc(mContext,new MinaResultLIstener() {
            @Override
            public void messageReceived(IoSession session, Object message) {


            }

            @Override
            public void exceptionCaught(IoSession session, Throwable cause) {


            }
        });
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        MianManager.getManager().shutDown();

        Intent intent = new Intent(mContext, MainActivity.class);
        LogUtils.v(TAG+"resAuthBean:"+resAuthBean.toString());
//        Bundle  mBundle = new Bundle();
//        mBundle.putSerializable("resAuthBeanlist", (Serializable) resAuthBeanlist);
//        intent.putExtras(mBundle);
        intent.putExtra("resAuthBean", resAuthBean);
        startActivity(intent);
        finish();
    }

    public class MyTextWatcher1 implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            LogUtils.v(TAG + "s:" + s);
            walletname = s.toString().trim();
            pwinfo = et_pwinfo.getText().toString().trim();
            canClick(walletname);
        }

        @Override
        public void afterTextChanged(Editable s) {


        }
    }


    public class MyTextWatcher2 implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            LogUtils.v(TAG + "s:" + s);
            walletname = et_name.getText().toString().trim();
            pwinfo = s.toString().trim();
//            canClick(pwinfo);
        }

        @Override
        public void afterTextChanged(Editable s) {


        }
    }


    private void canClick(String walletname) {


        if (null == walletname || "".equals(walletname)) {

            btn_createwallet.setBackground(getDrawable(R.drawable.btn_no_click_auth));
            btn_createwallet.setEnabled(false);

        } else {

            btn_createwallet.setBackground(getDrawable(R.drawable.btn_click_auth));
            btn_createwallet.setEnabled(true);
        }


    }


}